package Servlet;

import Bean.Employee;
import Utils.DateConvertor;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.hsf.HSFJSONUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;

@WebServlet("/emp1")
public class ServletEmployee1 extends HttpServlet {
	/**
	 * 这里还没有写完，是因为在进行跨域问题
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json;charset=UTF-8");
		resp.setHeader("Access-Control-Allow-Origin","*");
		//Json请求参数的获取
		//1.json请求参数肯定在请求体中，也就是说请求方式必须为post
		//2.读取请求体的内容
		//    获取输入流，req.getInputStream(),转换成json字符串
		//3.fastJson解析json字符串      JSONObject
		//4. BeanUtils.populate(bean,JSONObject);
		StringBuilder stringBuilder=new StringBuilder();
		ServletInputStream inputStream=req.getInputStream();
		InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
		BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
		while((bufferedReader.readLine())!=null) {
			stringBuilder.append(bufferedReader.readLine());
		}
		//现在将内容读取出来了
		//转成字符串
		String josnsStr =stringBuilder.toString();
		//转成字符串之后，转成对象

		//获取这个字符串的真实类型，然后再进行强制转换
		System.out.println(josnsStr.getClass());

		//在上面的类型中，得知这个类型是实现了，Map的接口的，所以它本身就是一个key-value结构
		JSONObject jsonObject=(JSONObject) JSONObject.parse(josnsStr);

		ConvertUtils.register(new DateConvertor("yyyy-MM-dd"),Date.class);

		Employee employee=new Employee();

		try {
			BeanUtils.populate(employee,jsonObject);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		//再将这个对象转换成字符串写回去
		String jsonStrResponse=JSONObject.toJSONString(employee);
		resp.getWriter().write(jsonStrResponse);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req,resp);
	}
}
